package sch.frog.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期操作工具类
 */
public class DateUtil {
	public static enum SpanType{
		MILLISECOND,
		DAY,
		MONTH,
		YEAR
	}
	
	public static enum WeekType{
		Sunday("星期日"),
		Monday("星期一"),
		Tuesday("星期二"),
		Wednesday("星期三"),
		Thursday("星期四"),
		Friday("星期五"),
		Saturday("星期六");
		
		private String name;

		private WeekType(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}
		
	}
	
	/**
	 * 一天的毫秒值
	 */
	public final static long ONE_DAY_MILLISECOND = 24 * 60 * 60 * 1000L;
	
	/**
	 * 获得当前所处年份
	 * @return 当前年份
	 */
	public static int getCurrentYear(){
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.YEAR);
	}
	
	/**
	 * 获得当前所处月份
	 * @return 当前月份
	 */
	public static int getCurrentMonth(){
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.MONTH) + 1;
	}
	
	/**
	 * 获得当前日期
	 * @return 当前日期
	 */
	public static int getCurrentDay(){
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.DATE);
	}
	
	/**
	 * 获得当前星期
	 * @return 当前星期
	 */
	public static WeekType getCurrentWeek(){
		Calendar calendar = Calendar.getInstance();
		int week = calendar.get(Calendar.DAY_OF_WEEK);
		return WeekType.values()[week - 1];
	}
	
	/**
	 * 判断一个年份是否是闰年
	 * @param year 要判断的年份
	 * @return 是闰年返回true
	 */
	public static boolean isLeapYear(int year){
		return  (year % 100 != 0 && year % 4 == 0) || (year % 400 == 0);
	}
	
    /**
     * 获得当前时间距离给定天数零点的毫秒时间
     * 
     * @param amount
     * @return
     */
    public static Long getDelayTime(int amount) {
        // 1 设置当前时间
        Calendar calendar = Calendar.getInstance();
        Date newDate = new Date();
        calendar.setTime(newDate);
        // 2 将时分秒设置成0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        // 3 设置指定天数
        calendar.add(Calendar.DATE, amount);
        // 4 计算当前时间距离设置日期零点的延迟时间
        return calendar.getTimeInMillis() - newDate.getTime();
    }
    
    /**
     * 将指定的字符串转为日期
     * @param date 要转换的字符串
     * @param pattern 转换后的日期
     * @return 转换后的日期对象
     */
    public static Date String2Date(String date, String pattern){
    	if(date == null) return null;
    	SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    	try {
			return sdf.parse(date);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
    }
    
    /**
     * 将指定的日期对象转为字符串
     * @param date 待转换的字符串
     * @param pattern 输出的格式
     * @return 转换后的字符串
     */
    public static String Date2String(Date date, String pattern){
    	if(date == null) return null;
    	SimpleDateFormat sdf = new SimpleDateFormat(pattern);
    	String format = sdf.format(date);
    	return format;
    }
}
